import App, {AppContext} from 'next/app';
import React from 'react';
import {initializeStore, Store} from '../lib/stores';
import {Provider} from 'mobx-react';
import Router from 'next/router';
import * as NProgress from 'nprogress';
import './_app.scss';

Router.events.on('routeChangeStart', url => {
	console.error(`Loading: ${url}`);
	NProgress.start();
});
Router.events.on('routeChangeComplete', () => NProgress.done());
Router.events.on('routeChangeError', () => NProgress.done());

class MyMobxApp extends App {

	mobxStore: Store;

	// Fetching serialized(JSON) store state
	static async getInitialProps(appContext: AppContext): Promise<any> {
		const ctx: any = appContext.ctx;
		// Comment 1 这里会做初始化。。。。
		ctx.mobxStore = initializeStore();// {DemoStore:{name:"123123"}}
		const appProps = await App.getInitialProps(appContext);
		// 创建（服务端）或获取（客户端）store对象命名为mobxStore，将mobxStore挂载到appContext.ctx对象上，这个对象会在页面的getInitialProps方法中作为入参传入
		return {
			...appProps,
			initialMobxState: ctx.mobxStore
		};
	}

	constructor(props: any) {
		super(props);
		// Comment 2
		const isServer = typeof window === 'undefined';
		this.mobxStore = isServer ? props.initialMobxState : initializeStore(props.initialMobxState);
	}

	render() {
		const {Component, pageProps}: any = this.props;
		return (
			// 全局配置 前端的配置。
			<Provider {...this.mobxStore}>
				<Component {...pageProps} />
			</Provider>
		);
	}
}

export default MyMobxApp;
